//
//  RegisterViewController.m
//  TodatPlay
//
//  Created by dllo on 16/9/16.
//  Copyright © 2016年 DM.C. All rights reserved.
//

#import "RegisterViewController.h"
#import "AFNetworking.h"
@interface RegisterViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *seccodeTextField;
@property (weak, nonatomic) IBOutlet UITextField *inputPassWord;
@property (weak, nonatomic) IBOutlet UITextField *makeSureTextField;
@property (weak, nonatomic) IBOutlet UIButton *getCode;

@property (weak, nonatomic) IBOutlet UIButton *selectedButton;

@end

@implementation RegisterViewController {
    int secondsCountDown; //倒计时总时长
    NSTimer *countDownTimer;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    // 使状态栏颜色为白色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
}


-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    // 是的状态栏颜色为黑色
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
}


#pragma mark - 阅读并同意服务条款
- (IBAction)didSelected:(id)sender {
    [self.selectedButton setImage:[UIImage imageNamed:@"order_selected_normal"] forState:UIControlStateNormal];
    [sender removeTarget:self action:@selector(didSelected:) forControlEvents:UIControlEventTouchUpInside];
    [self.selectedButton addTarget:self action:@selector(agree:) forControlEvents:UIControlEventTouchUpInside];
    
    
}
- (void)agree:(UIButton *)btn {
    [self.selectedButton setImage:[UIImage imageNamed:@"order_selected_press"] forState:UIControlStateNormal];
    [btn removeTarget:self action:@selector(agree:) forControlEvents:UIControlEventTouchUpInside];
    [self.selectedButton addTarget:self action:@selector(didSelected:) forControlEvents:UIControlEventTouchUpInside];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"注册";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icons_back_dark"] style:UIBarButtonItemStylePlain target:self action:@selector(handleLeft:)];
    

    self.getCode.layer.cornerRadius = self.getCode.frame.size.height / 2.0;
    self.getCode.layer.borderWidth = 1;
    self.getCode.layer.borderColor = [UIColor blackColor].CGColor;

    self.phoneNumberTextField.delegate = self;
    self.makeSureTextField.delegate = self;
    
    self.phoneNumberTextField.keyboardType = UIKeyboardTypePhonePad;
    self.seccodeTextField.keyboardType = UIKeyboardTypePhonePad;
    self.inputPassWord.secureTextEntry = YES;
    self.makeSureTextField.secureTextEntry = YES;
    
}
- (void)handleLeft:(UIBarButtonItem *)btn {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - textfieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (self.makeSureTextField.text != self.inputPassWord.text) {
        NSLog(@"两次密码输入不一样");
    }
    if ([self valiMobile:self.phoneNumberTextField.text]) {
        NSLog(@"这个是电话号");
    } else {
        NSLog(@"这个不是电话号");
    }
    
    if (self.inputPassWord.text.length < 6 && self.inputPassWord.text.length > 16) {
        self.makeSureTextField.placeholder = @"密码长度不正确";
    }
    
}
// 通过正则表达式判断电话输入框中的内容是否是电话号
- (BOOL)valiMobile:(NSString *)mobile{
    
    if (mobile.length != 11)
    {
        return NO;
    }else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

- (IBAction)getCode:(id)sender {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postURLString = @"http://wanapi.damai.cn/user/regbycode.json";
    NSString *parameters = @"platform=4&phone=15998571702&channel_from=m360_market&source=10345&version=203004";
    // 将字符串parameters通过@"&"分割放入数组中
    NSArray *parametersArr = [parameters componentsSeparatedByString:@"&"];
    NSMutableString *newParameter = [NSMutableString new];
    for (NSString *parameter in parametersArr) {
        if ([parameter containsString:@"platform"]) {
            [newParameter appendString:parameter];
        } else if ([parameter containsString:@"phone"]) {
            NSArray *phoneArr = [parameter componentsSeparatedByString:@"="];
            NSString *phoneStr = phoneArr[0];
            phoneStr = [phoneStr stringByAppendingFormat:@"=%@", self.phoneNumberTextField.text];
            [newParameter appendFormat:@"&%@", phoneStr];
        } else {
            [newParameter appendFormat:@"&%@", parameter];
        }
    }
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    // 3. 设置请求参数的字符串格式, 自定义
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return parameters;
    }];
    NSMutableSet *set = [NSMutableSet setWithSet:manager.responseSerializer.acceptableContentTypes];
    [set addObject:@"text/html"];
    [manager.responseSerializer setAcceptableContentTypes:set];
    
    [manager GET:postURLString parameters:newParameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"发送验证码请求成功: %@", responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"发送验证码请求失败: %@", error);
    }];
    
   
    // 倒计时
    //设置倒计时总时长
    secondsCountDown = 60;//60秒倒计时
    //开始倒计时
    countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES]; //启动倒计时后会每秒钟调用一次方法 timeFireMethod
    //设置倒计时显示的时间
    NSString *timeStr = [NSString stringWithFormat:@"%ds",secondsCountDown]; ;
    [self.getCode setTitle:timeStr forState:UIControlStateNormal];
    [self.getCode removeTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark - 实现倒计时方法
-(void)timeFireMethod{
    //倒计时-1
    secondsCountDown--;
    //修改倒计时标签现实内容
    NSString *timeStr = [NSString stringWithFormat:@"%ds",secondsCountDown]; ;
    [self.getCode setTitle:timeStr forState:UIControlStateNormal];
    
    //当倒计时到0时，做需要的操作，比如验证码过期不能提交
    if(secondsCountDown==0){
        [countDownTimer invalidate];
        [self.getCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.getCode addTarget:self action:@selector(getCode:) forControlEvents:UIControlEventTouchUpInside];
    }
}

- (IBAction)registerButton:(id)sender {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString *postURLString = @"http://wanapi.damai.cn/user/regnew.json";
    NSString *parameters = @"platform=4&source=10345&passwd=qweasdzxc&version=203004&phone=15998571702&gender=1&channel_from=m360_market&code=372332";
    // 拼接网址, 与输入框内容相同
    NSArray *parametersArr = [parameters componentsSeparatedByString:@"&"];
    NSMutableString *newParameter = [NSMutableString new];
    for (NSString *parameter in parametersArr) {
        if ([parameter containsString:@"platform"]) {
            [newParameter appendString:parameter];
        } else if ([parameter containsString:@"passwd"]) {
            NSArray *passwdArr = [NSArray array];
            passwdArr = [parameter componentsSeparatedByString:@"="];
            NSString *passwdStr = passwdArr[0];
            passwdStr = [passwdStr stringByAppendingFormat:@"=%@", self.makeSureTextField.text];
            [newParameter appendFormat:@"&%@", passwdStr];
            
        } else if ([parameter containsString:@"phone"]) {
            NSArray *phoneArr = [NSArray array];
            phoneArr = [parameter componentsSeparatedByString:@"="];
            NSString *phoneStr = phoneArr[0];
            phoneStr = [phoneStr stringByAppendingFormat:@"=%@", self.phoneNumberTextField.text];
            [newParameter appendFormat:@"&%@", phoneStr];
            
        } else if ([parameter containsString:@"code"]) {
            NSArray *codeArr = [NSArray array];
            codeArr = [parameter componentsSeparatedByString:@"="];
            NSString *codeStr = codeArr[0];
            codeStr = [codeStr stringByAppendingFormat:@"=%@", self.seccodeTextField.text];
            [newParameter appendFormat:@"&%@", codeStr];
        } else {
            [newParameter appendFormat:@"&%@", parameter];
        }
    }
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    // 3. 设置请求参数的字符串格式, 自定义
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
        return parameters;
    }];
    NSMutableSet *set = [NSMutableSet setWithSet:manager.responseSerializer.acceptableContentTypes];
    [set addObject:@"text/html"];
    [manager.responseSerializer setAcceptableContentTypes:set];
    
    [manager GET:postURLString parameters:newParameter progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"注册请求成功: %@", responseObject);
        // 取出返回的参数值
        NSString *mCode = responseObject[@"data"][@"M"];
        // 注册成功后自动登录
        NSString *postURLString = @"http://wanapi.damai.cn/user/myview.json";
        NSMutableArray *parametersArr = [NSMutableArray array];
        NSString *parameters = @"platform=4&channel_from=m360_market&source=10345&m=1e143f17ab1241d0b40e74d9e78aafaf&version=203004";
        // 将字符串通过&切割
        parametersArr = [parameters componentsSeparatedByString:@"&"].mutableCopy;
        NSMutableString *newParameters = [NSMutableString new];
        for (NSString *parameter in parametersArr) {
            if ([parameter containsString:@"platform"]) {
                [newParameters appendString:parameter];
            } else if ([parameter containsString:@"m=1e"]) {
                NSArray *mArr = [parameter componentsSeparatedByString:@"="];
                NSString *mStr = mArr[0];
                mStr = [mStr stringByAppendingFormat:@"=%@", mCode];
                [newParameters appendFormat:@"&%@", mStr];
            } else {
                [newParameters appendFormat:@"&%@", parameter];
            }
        }
        
        [manager GET:postURLString parameters:newParameters progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"返回都登录参数请求成功: %@", responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"返回都登录参数请求失败: %@", error);
        }];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"注册请求失败: %@", error);
    }];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
